//
//  HXQYPictureGatherViewController.m
//  KD
//
//  Created by 梅洋 on 16/7/28.
//  Copyright © 2016年 Whx. All rights reserved.
//

#import "HXQYPictureGatherViewController.h"
#import "HXQYPictureCollectionView.h"
#import "HXUpDataImageModel.h"
#import "Imitation_AlertView_TextField.h"
#import "HXReportEvidenceViewController.h"
#import "HXJobPunishDetailsModel.h"

@interface HXQYPictureGatherViewController ()<UINavigationControllerDelegate, UIImagePickerControllerDelegate,UITextViewDelegate,Imitation_AlertView_TextFielddelegate,UIScrollViewDelegate>

@property (nonatomic,copy) NSString * companyName;
@property (nonatomic,assign) QY_JUMP pushType;
@property (nonatomic,copy)  NSString * taskId;
@property (nonatomic,copy)  NSString * SiteWorkContent;
@property (nonatomic,copy)  NSString * sendTimeStr;//网络时间
@property (nonatomic,assign) BOOL   isFirstLoad;
@property (nonatomic,copy)  NSString * addressString;//当前位置
@property (nonatomic,copy)  NSString * dict_FilePath;//图片地址
@property (nonatomic,copy)  NSString * groupName;
@property (nonatomic,assign) BOOL   isCon_SendBtn;//是否为点击发布按钮


/**背景视图*/
@property (nonatomic,strong) UIScrollView * bgScrollView;
@property (nonatomic,strong) UILabel      * companyLabel;
@property (nonatomic,strong) UITextView   * textView;
@property (nonatomic,strong) UILabel      * placeholderLabel;

@property (nonatomic,strong) UIView       * bgView1;

@property (nonatomic,strong) UIImageView  * bigImgView;
//地址 时间 照片描述
@property (nonatomic,strong) UILabel      * addressLabel;
@property (nonatomic,strong) UILabel      * dateTimeLabel;
@property (nonatomic,strong) UILabel      * photoDetailLabel;

@property (nonatomic,strong) Imitation_AlertView_TextField * describeTextView;

//展示照片
@property (nonatomic,strong) HXQYPictureCollectionView * qyCollectionView;
@property (nonatomic,strong) NSMutableArray <HXJobPunishDetailsListModel *> * collectionViewDataArray;

@end

@implementation HXQYPictureGatherViewController

/**
 重写init方法 1.需要企业名称 2.push过来的类型
 */
-(instancetype)initWithCompanyName:(NSString *)companyName
                      withPushType:(QY_JUMP)pushType
                        withTaskId:(NSString *)taskid
               withSiteWorkContent:(NSString *)SiteWorkContent
                     withGroupName:(NSString *)groupName{

    if ([super init]) {
        
        self.companyName     = companyName;
        self.pushType        = pushType;
        self.taskId          = taskid;
        self.SiteWorkContent = SiteWorkContent;
        self.groupName       = groupName;
    }
    
    return self;
}

//懒加载
-(UIScrollView *)bgScrollView{

    if (_bgScrollView == nil) {
        
        _bgScrollView = [[UIScrollView alloc] initWithFrame:CGRectMake(0, 0, HXSCREEN_WIDTH, HXSCREEN_HEIGHT)];
        _bgScrollView.delegate = self;
        [self.view addSubview:_bgScrollView];
        _bgScrollView.contentSize = CGSizeMake(HXSCREEN_WIDTH, HXSCREEN_HEIGHT);
        
    }
    return _bgScrollView;
}
-(NSMutableArray<HXJobPunishDetailsListModel *> *)collectionViewDataArray{

    if (_collectionViewDataArray == nil) {
        
        _collectionViewDataArray = [[NSMutableArray alloc] init];
    }
    
    return _collectionViewDataArray;
}

- (void)scrollViewWillBeginDragging:(UIScrollView *)scrollView{

    [self.view endEditing:YES];
}

/**设置页面布局*/
-(void)loadCreateViewController:(BOOL)isUsed{

    if (_companyLabel == nil) {
        
        NSString * companyStr = [NSString stringWithFormat:@"企业名称: %@",self.companyName];
        NSMutableAttributedString * commpanyAttributeStr = [[NSMutableAttributedString alloc] initWithString:companyStr];
        [commpanyAttributeStr addAttribute:NSFontAttributeName
                                     value:[UIFont fontWithName:@"Helvetica-Bold" size:16]
                                     range:NSMakeRange(5, commpanyAttributeStr.length-5)];
        [commpanyAttributeStr addAttribute:NSFontAttributeName
                                     value:[UIFont systemFontOfSize:14]
                                     range:NSMakeRange(0, 5)];
        
        CGFloat companyHeight = [companyStr heightWithFont:[UIFont systemFontOfSize:18] withinWidth:HXSCREEN_WIDTH-8.f*2-8.f*3];
        companyHeight = companyHeight > 36 ? companyHeight : 36;
        _companyLabel = [[UILabel alloc] initWithFrame:CGRectMake(8.f, 8.f, HXSCREEN_WIDTH-8.f*2, companyHeight)];
        [self.bgScrollView addSubview:_companyLabel];
//        _companyLabel.layer.borderWidth = 0.5;
//        _companyLabel.layer.borderColor = [UIColor lightGrayColor].CGColor;
        _companyLabel.attributedText    = commpanyAttributeStr;
        _companyLabel.numberOfLines     = 0;
    }
    
    if (_textView == nil) {
        
        UILabel * label = [[UILabel alloc] initWithFrame:CGRectMake(8.f, _companyLabel.bottom + 4.f, _companyLabel.width, 16)];
        [self.bgScrollView addSubview:label];
        label.text      = @"工作内容描述:";
        label.font      = [UIFont systemFontOfSize:14];
        label.textColor = [UIColor blackColor];
        label.backgroundColor = [UIColor clearColor];
        
        CGFloat textViewHight = [self.SiteWorkContent heightWithFont:[UIFont systemFontOfSize:17] withinWidth:_companyLabel.width-8.f];
        textViewHight = textViewHight > 100 ? textViewHight : 100;
        _textView = [[UITextView alloc] initWithFrame:CGRectMake(8.f, label.bottom+8.f, _companyLabel.width, textViewHight)];
        [self.bgScrollView addSubview:_textView];
        _textView.layer.borderWidth = 0.5;
        _textView.layer.borderColor = [UIColor lightGrayColor].CGColor;
        _textView.font = [UIFont systemFontOfSize:16];
        _textView.text = self.SiteWorkContent;
        _textView.tag  = 10000;
        //设置placeholder
        _placeholderLabel = [[UILabel alloc] initWithFrame:CGRectMake(12.f, _textView.top+8.f, 200, 21)];
        _placeholderLabel.text = @"请输入...";
        _placeholderLabel.font = [UIFont systemFontOfSize:14];
        [self.bgScrollView addSubview:_placeholderLabel];
        _placeholderLabel.textColor = [UIColor lightGrayColor];
        if (self.SiteWorkContent.length != 0) {
            _placeholderLabel.hidden = YES;
        }
        _textView.userInteractionEnabled = isUsed;
    }
    if (_bgView1 == nil) {
        
        _bgView1 = [[UIView alloc] initWithFrame:CGRectMake(8.f, _textView.bottom+4.f, HXSCREEN_WIDTH-8*2, 560)];
        [self.bgScrollView addSubview:_bgView1];
//        _bgView1.backgroundColor = [UIColor lightGrayColor];
    }
    
    if (_bigImgView == nil) {
        
        UILabel * xcqzLabel = [[UILabel alloc] initWithFrame:CGRectMake(0.f, 0.f, _bgView1.width, 56)];
        [_bgView1 addSubview:xcqzLabel];
        xcqzLabel.text = @"现场取证";
        xcqzLabel.textAlignment = NSTextAlignmentCenter;
        xcqzLabel.font = [UIFont fontWithName:@"Arial-BoldMT" size:24];
        
        _bigImgView = [[UIImageView alloc] initWithFrame:CGRectMake((_bgView1.width-275)/2, xcqzLabel.bottom, 275, 200)];
        [_bgView1 addSubview:_bigImgView];
//        _bigImgView.backgroundColor = [UIColor redColor];
        //_bigImgView.image = [UIImage imageNamed:@"bg"];
        _bigImgView.userInteractionEnabled = YES;
        
        UIButton * bigImgVBtn = [[UIButton alloc] initWithFrame:_bigImgView.bounds];
        [_bigImgView addSubview:bigImgVBtn];
//        bigImgVBtn.backgroundColor = [UIColor whiteColor];
        [bigImgVBtn setImage:[UIImage imageNamed:@"Site+"] forState:UIControlStateNormal];
        [bigImgVBtn addTarget:self action:@selector(bigImgVBtnAct:) forControlEvents:UIControlEventTouchUpInside];
        
        bigImgVBtn.userInteractionEnabled = isUsed;
    }
    
    //取证信息
    if (_addressLabel == nil) {
        
        UILabel * qzxxLabel = [[UILabel alloc] initWithFrame:CGRectMake(0.f, _bigImgView.bottom+8.f, _bgView1.width, 24)];
        qzxxLabel.text = @"取证信息";
        [_bgView1 addSubview:qzxxLabel];
        qzxxLabel.textAlignment = NSTextAlignmentLeft;
        qzxxLabel.font = [UIFont fontWithName:@"Arial-BoldMT" size:19];
        
        //地址
        _addressLabel = [[UILabel alloc] initWithFrame:CGRectMake(0.f, qzxxLabel.bottom+4.f, _bgView1.width, 34)];
        _addressLabel.text = @"公司地址: ";
        [_bgView1 addSubview:_addressLabel];
        _addressLabel.numberOfLines = 0;
        _addressLabel.font = [UIFont systemFontOfSize:14];
        
        //时间
        _dateTimeLabel = [[UILabel alloc] initWithFrame:CGRectMake(0.f, _addressLabel.bottom+4.f, _bgView1.width, 24)];
        _dateTimeLabel.text = @"取证时间: ";
        [_bgView1 addSubview:_dateTimeLabel];
        _dateTimeLabel.font = [UIFont systemFontOfSize:14];

        
        //照片描述
        _photoDetailLabel = [[UILabel alloc] initWithFrame:CGRectMake(0.f, _dateTimeLabel.bottom+4.f, _bgView1.width, 35)];
        [_bgView1 addSubview:_photoDetailLabel];
        _photoDetailLabel.text = @"照片描述: ";
        _photoDetailLabel.numberOfLines = 0;
        _photoDetailLabel.font = [UIFont systemFontOfSize:14];

    }
    
    if (_qyCollectionView == nil) {
        
        _qyCollectionView = [[HXQYPictureCollectionView alloc] initWithFrame:CGRectMake(0.f, _photoDetailLabel.bottom + 8.f, _bgView1.width, 108) withIsUsed:isUsed withHXCollectionViewType:HXCVTYPE_QYPictureGather];
        [_bgView1 addSubview:_qyCollectionView];
        
        //block  点击单元格返回 model数据
        [_qyCollectionView SelectReturnTapCell:^(HXJobPunishDetailsListModel *listModel) {
            
            [self loadCreateShowSendPicInfo:listModel];
        }];
        
        //block  长按单元格返回 数据源数组 及 删除的坐标
        [_qyCollectionView ReturnDeleteDataArray:^(NSMutableArray<HXJobPunishDetailsListModel *> *modelDataArray, NSInteger firstIndex) {
            
            [self.collectionViewDataArray removeAllObjects];
            self.collectionViewDataArray = modelDataArray;
            self.qyCollectionView.dataArray = modelDataArray;
            if (firstIndex == 0) {
                
                if (self.collectionViewDataArray.count > 0) {
                    
                    [self loadCreateShowSendPicInfo:self.collectionViewDataArray[firstIndex]];
                }else{
                    
                    [self loadCreateShowSendPicInfo:nil];
                }
                
            }else{
                
                [self loadCreateShowSendPicInfo:self.collectionViewDataArray[firstIndex-1]];
            }
            
        }];
        
        if (isUsed) {
            
            UIButton * finishBtn = [[UIButton alloc] initWithFrame:CGRectMake(0.f, _qyCollectionView.bottom+16.f, _bgView1.width, 36)];
            [_bgView1 addSubview:finishBtn];
            finishBtn.backgroundColor = [UIColor blueColor];
            [finishBtn setTitle:@"发布" forState:UIControlStateNormal];
            [finishBtn setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
            [finishBtn addTarget:self action:@selector(finishBtnAct:) forControlEvents:UIControlEventTouchUpInside];
            finishBtn.tag = 101;
        }
        
    }
    if (_describeTextView == nil) {
        
        _describeTextView = [[Imitation_AlertView_TextField alloc] initWithFatherViewFrameWidth:HXSCREEN_WIDTH withFrameHeight:HXSCREEN_HEIGHT];
        _describeTextView.title = @"照片描述";
        _describeTextView.delegate = self;
        [_describeTextView viewHidden];
    }
    
    //背景视图的 内容尺寸
    CGFloat contentSizeHeight = _companyLabel.height + _bgView1.height + _textView.height + 40+120;
    if (contentSizeHeight <= HXSCREEN_HEIGHT) {
        contentSizeHeight = HXSCREEN_HEIGHT+100;
    }
    self.bgScrollView.contentSize = CGSizeMake(HXSCREEN_WIDTH, contentSizeHeight);

}

//textview改变字体通知
-(void)textViewTextDidChange:(NSNotification *)notification{
    
    
    UITextView * textView = (UITextView *)notification.object;
    
    if (textView.tag == 10000) {
        
        CGFloat textViewHight = 0;
        if (textView.text.length == 0) {
            _placeholderLabel.hidden = NO;
            //        CGRect oldFrame = _textView.frame;
            //        oldFrame.size.height = 100;
            //        _textView.frame = oldFrame;
            //
            //        CGRect bgView1OldFrame = _bgView1.frame;
            //        bgView1OldFrame.origin.y = _textView.bottom+4.f;
            //        _bgView1.frame = bgView1OldFrame;
            
        }else{
            
            _placeholderLabel.hidden = YES;
            textViewHight = [textView.text heightWithFont:[UIFont systemFontOfSize:17] withinWidth:_companyLabel.width-8.f];
            
            if (textViewHight > 100) {
                CGRect oldFrame = _textView.frame;
                oldFrame.size.height = textViewHight;
                _textView.frame = oldFrame;
                
                CGRect bgView1OldFrame = _bgView1.frame;
                bgView1OldFrame.origin.y = _textView.bottom+4.f;
                _bgView1.frame = bgView1OldFrame;
                
            }else{
                
                CGRect oldFrame = _textView.frame;
                oldFrame.size.height = 100;
                _textView.frame = oldFrame;
                
                CGRect bgView1OldFrame = _bgView1.frame;
                bgView1OldFrame.origin.y = _textView.bottom+4.f;
                _bgView1.frame = bgView1OldFrame;
                
            }
            
            //背景视图的 内容尺寸
            CGFloat contentSizeHeight = _companyLabel.height + _bgView1.height + _textView.height + 40+120;
            if (contentSizeHeight <= HXSCREEN_HEIGHT) {
                contentSizeHeight = HXSCREEN_HEIGHT+100;
            }
            self.bgScrollView.contentSize = CGSizeMake(HXSCREEN_WIDTH, contentSizeHeight);
        }
    }
}

/**展示 图文详情*/
-(void)loadCreateShowSendPicInfo:(HXJobPunishDetailsListModel *)listModel{

    
    if (listModel == nil) {
        //地址
        self.addressLabel.text = @"公司地址: ";
        //发送时间
        self.dateTimeLabel.text = @"发送时间: ";
        //照片描述
        self.photoDetailLabel.text = @"照片描述: ";
        //大照片
        self.bigImgView.image = [[UIImage alloc] init];

    }else{
    
        //地址
        self.addressLabel.text = [NSString stringWithFormat:@"公司地址: %@",listModel.Con_Add];
        //发送时间
        self.dateTimeLabel.text = [NSString stringWithFormat:@"发送时间: %@",listModel.Con_Date];
        //照片描述
        self.photoDetailLabel.text = [NSString stringWithFormat:@"照片描述: %@",listModel.Con_Content];
        //大照片
        [self.bigImgView sd_setImageWithURL:[NSURL URLWithString:listModel.Con_PicUrl] placeholderImage:nil];
    }
    
}

/**发布按钮的点击响应事件*/
-(void)finishBtnAct:(UIButton *)sender{
    
    [NetworkAPI changePresonTaskContentWithTaskID:self.taskId
                                         SiteName:_textView.text
                                        GroupName:self.groupName
                                       SubmitDate:@""
                                          Success:^(HXBaseModel *result) {
                                          }
                                          failure:^(NSError *err) {
                                              
                                          }];


    if (self.collectionViewDataArray.count <= 0) {
        
        [NetworkAPI deleteDoorPhotoWithTaskID:self.taskId
                                      PicType:@"4" Success:^(HXBaseModel *result) {
                                         
                                          if ([result.code integerValue] == 200) {
                                              [self tanchuangshitu:@"删除成功,是否退出?"];
                                              [self.navigationController popViewControllerAnimated:YES];
                                          }else if([result.code integerValue] == 500){
                                          
                                              [LTAlertView showTitle:@"⚠️"
                                                             message:@"请完善相关信息后,再次提交!"
                                                        ButtonTitles:@[@"确定"]
                                                          OnTapBlock:^(LTAlertView *alert, NSInteger num) {
                                                              
                                                          }];
                                          }
                                          
                                      } failure:^(NSError *err) {
                                          [SVProgressHUD showErrorWithStatus:@"对不起!网络错误..."];
                                      }];
    }else{
    
        self.isCon_SendBtn = YES;
        [self loadCreatePicUpload];
    }
}

/**上传数据 转化为 字典形式*/
-(NSMutableDictionary *)finalDataTransformDic{

    NSMutableArray * dicArray = [NSMutableArray array];
    
    for (HXJobPunishDetailsListModel * listModel in self.collectionViewDataArray) {
        
        NSDictionary * dic = @{
                               @"Con_TaskID":listModel.Con_TaskID,
                               @"Con_UserID":[UserDefaultHandler getUserDetault:kID],
                               @"Con_Title":listModel.Con_Title,
                               @"Con_Add":listModel.Con_Add,
                               @"Con_Content":listModel.Con_Content,
                               @"Con_Date":listModel.Con_Date,
                               @"Con_PicUrl":listModel.Con_PicUrl,
                               @"Con_PicType":@"4",
                               @"Con_IsSend":@"true",
                               };
        
        [dicArray addObject:dic];
    }
    
    
    return [NSMutableDictionary dictionaryWithObject:dicArray forKey:@"dict"];
}

/**
 添加照片
 */
-(void)bigImgVBtnAct:(UIButton *)sender{

    [self.view endEditing:YES];
    CTActionSheet *actionSheet = [CTActionSheet actionSheetWithTitle:nil cancelButtonTitle:@"取消" destructiveButtonTitle:@"拍照" otherButtonTitles:@"从相机相册选择" HandleBlock:^(int btnIndex) {
        if (btnIndex == 0) {
            if ([UIImagePickerController isSourceTypeAvailable:UIImagePickerControllerSourceTypeCamera]) {
                UIImagePickerControllerSourceType sourceType = UIImagePickerControllerSourceTypeCamera;
                UIImagePickerController *picker = [[UIImagePickerController alloc] init];//初始化
                picker.delegate = self;
                picker.allowsEditing = YES;//设置可编辑
                picker.sourceType = sourceType;
                [self presentViewController:picker animated:YES completion:^{
                }];//进入照相界面
            }
        }else if (btnIndex == 1){
            UIImagePickerController *pickerImage = [[UIImagePickerController alloc] init];
            if([UIImagePickerController isSourceTypeAvailable:UIImagePickerControllerSourceTypePhotoLibrary]) {
                pickerImage.sourceType = UIImagePickerControllerSourceTypePhotoLibrary;
                pickerImage.mediaTypes = [UIImagePickerController availableMediaTypesForSourceType:pickerImage.sourceType];
            }
            pickerImage.delegate = self;
            pickerImage.allowsEditing = YES;
            [self presentViewController:pickerImage animated:YES completion:^{
            }];
        }else{
        }
    }];
    UIWindow* window = [[[UIApplication sharedApplication] delegate] window];
    if ([window.subviews containsObject:self.view]) {
        [actionSheet showInView:self.view];
    } else {
        [actionSheet showInView:window];
    }
}

- (void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary *)info{
    UIImage *originalImage =  (UIImage *) [info objectForKey:UIImagePickerControllerEditedImage];
   
    if(!originalImage){
        originalImage = (UIImage *) [info objectForKey:UIImagePickerControllerOriginalImage];
    }
    //拿到照片后
    [self setUpIconBtnWithImage:originalImage];
    [picker dismissViewControllerAnimated:YES completion:nil];
}

//设置并上传图片
-(void)setUpIconBtnWithImage:(UIImage *)image{
    [self getNetTime];
    NSData *imageData = UIImageJPEGRepresentation(image, 1);
    if  (imageData.length>300000){
        UIImage *image = [UIImage imageWithData:imageData];
        imageData = UIImageJPEGRepresentation(image, 0.005);
    }
    if (self.addressString == nil) {
        
        self.addressString = [[NSUserDefaults standardUserDefaults] objectForKey:CCLastAddress];
    }
    self.dateTimeLabel.text =  [NSString stringWithFormat:@"发送时间: %@",self.sendTimeStr];
    self.addressLabel.text = [NSString stringWithFormat:@"公司地址: %@",self.addressString];
    //1。创建管理者对象
    AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
    manager.responseSerializer.acceptableContentTypes = [manager.responseSerializer.acceptableContentTypes setByAddingObjectsFromArray:@[@"application/json", @"text/json",@"text/html", @"text/javascript", @"text/plain"]];
    [manager POST:[NSString stringWithFormat:@"%@/Work/SendPic.ashx",API_HOST] parameters:nil constructingBodyWithBlock:^(id<AFMultipartFormData>  _Nonnull formData) {
        [formData appendPartWithFileData:imageData name:@"img" fileName:@"name" mimeType:@"image/png"];
    } progress:^(NSProgress * _Nonnull uploadProgress) {
    } success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        HXUpDataImageModel * dict = [[HXUpDataImageModel alloc] initWithDictionary:responseObject error:nil];
        if ([dict.code isEqualToString:@"200"]) {
            [SVProgressHUD showSuccessWithStatus:@"图片上传成功"];
            self.dict_FilePath = dict.FilePath;
            [_describeTextView viewShow];
        }
        else{
            [SVProgressHUD showErrorWithStatus:@"图片上传失败"];
        }
        
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        [SVProgressHUD showErrorWithStatus:@"图上传失败"];
    }];
}

#pragma mark ------------// Imitation_AlertView_TextFielddelegate \\-------------
- (void)at_textViewDidEndEditingWithView:(UIView *) alertView withTextView:(UITextView *)at_textView {
    
    self.photoDetailLabel.text = [NSString stringWithFormat:@"照片描述: %@",at_textView.text];
    [self loadCreateCunCuShuJuYuan:at_textView.text];
}
- (void)at_textViewDidViewHidden:(UIView *)alertView withTextView:(UITextView *)at_textView{
    
    self.photoDetailLabel.text = @"照片描述:暂无描述";
    [self loadCreateCunCuShuJuYuan:@""];
}
-(void)loadCreateCunCuShuJuYuan:(NSString *)at_text{

    HXJobPunishDetailsListModel * model = [[HXJobPunishDetailsListModel alloc] initWithCon_TaskID:self.taskId withCon_Title:self.companyName withCon_Add:self.addressString withCon_Content:at_text withCon_Date:self.sendTimeStr withCon_PicUrl:self.dict_FilePath withCon_PicType:@"" withCon_IsPunish:@"" withCon_Pic:@"" withCon_PunishID:@"" withCon_IsSend:@"" withCon_PunishContent:@"" withCon_ChangeStart:@"" withCon_ChangeEnd:@"" withImg_Url:@"true"];
    
    [self.collectionViewDataArray addObject:model];
    self.qyCollectionView.dataArray = self.collectionViewDataArray;
    [self.bigImgView sd_setImageWithURL:[NSURL URLWithString:self.dict_FilePath] placeholderImage:nil];
    
    [self loadCreatePicUpload];
}

/**上传图片到服务器*/
-(void)loadCreatePicUpload{

    [NetworkAPI createAddWithDic:[self finalDataTransformDic]
                         success:^(HXSendInformationModel *result) {

                             if (self.isCon_SendBtn) {
                                 if ([result.code integerValue] == 200) {
                                     
                                     [self tanchuangshitu:@"发布成功,是否退出?"];
                                     
                                 }else{
                                     [SVProgressHUD showErrorWithStatus:@"对不起!网络错误..."];
                                 }
                             }
                         }
                         failure:^(NSError *err) {
                             if (self.isCon_SendBtn) {
                                 [SVProgressHUD showErrorWithStatus:@"对不起!网络错误..."];
                             }
                         }];
}

-(void)tanchuangshitu:(NSString *)tishiStr {
    UIAlertController *alertController=[UIAlertController alertControllerWithTitle:tishiStr message:nil preferredStyle:UIAlertControllerStyleAlert];
    UIAlertAction *cancelButton=[UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleCancel handler:^(UIAlertAction *action) {
    }];
    UIAlertAction *cretainButtn=[UIAlertAction actionWithTitle:@"确定" style:UIAlertActionStyleDestructive handler:^(UIAlertAction *action) {
        //点击按钮之后 回调的bolck
        [self.navigationController popViewControllerAnimated:YES];
    }];
    [alertController addAction:cancelButton];
    [alertController addAction:cretainButtn];
    [self presentViewController:alertController animated:YES completion:^{
        
    }];
}

/**
 获取网络时间
 */
-(void)getNetTime {
    if (self.isFirstLoad) {
        [SVProgressHUD showWithStatus:@"正在加载数据,请稍后..."];
    }
    [NetworkAPI getServerDateSuccess:^(HXServerDateModel *result) {
        if ([result.code isEqualToString:@"200"]) {
            self.sendTimeStr = result.ServerDate;
            if (self.isFirstLoad) {
                [self loadCreateGetTaskDetail];
            }
        }
    } failure:^(NSError *err) {
        [SVProgressHUD showErrorWithStatus:@"获取网络时间失败,请检查网络"];
    }];
}

- (void) loadCreateNav{

    self.navigationItem.title = @"企业检查";
    self.view.backgroundColor = [UIColor whiteColor];
    self.navigationController.navigationBar.translucent = YES;
    //创建右侧的按钮 --- 只有从列表push过来的才可以显示
    if (self.pushType == QY_JUMP_LISTRESULT) {
        
        //右侧的bar按钮
        self.navigationItem.rightBarButtonItem = [[UIBarButtonItem alloc] initWithTitle:@"报告取证" style:UIBarButtonItemStylePlain target:self action:@selector(baoGaoQuZhengBtnAct)];
    }

//#pragma mark ----------LeftBarBtn ----------------
//    
//    UIButton *backButton=[[UIButton alloc]init];
//    // 设置返回图片
//    [backButton setImage:[UIImage imageNamed:@"nav_back"] forState:UIControlStateNormal];
//    backButton.contentMode = UIViewContentModeLeft;
//    backButton.contentHorizontalAlignment = UIControlContentHorizontalAlignmentLeft;
//    // [button sizeToFit];//让按钮大小跟随内容
//    // 让按钮的内容往左边偏移10
//    backButton.contentEdgeInsets = UIEdgeInsetsMake(0, -10, 0, 0);
//    [backButton addTarget:self action:@selector(finishBtnAct:) forControlEvents:UIControlEventTouchUpInside];
//    backButton.tag  = 100;
//    backButton.frame=CGRectMake(0, 0,37,90);
//    self.navigationItem.leftBarButtonItem=[[UIBarButtonItem alloc]initWithCustomView:backButton];
}

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    self.isFirstLoad = YES;
    self.isCon_SendBtn = NO;
    //注册Textview的通知
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(textViewTextDidChange:) name:UITextViewTextDidChangeNotification object:nil];
    
    [[CCLocationManager shareLocation] getAddress:^(NSString *addressString) {
        self.addressString = addressString;
    }];
    
    //获取网络时间
    [self getNetTime];
    [self loadCreateNav];
}

/**加载数据*/
-(void)loadCreateGetTaskDetail{
    
    self.isFirstLoad = NO;
    if (self.pushType == QY_JUMP_LISTRESULT) {
        [NetworkAPI getTaskDescribeWithTaskID:self.taskId
                                      Success:^(HXTaskDescribeModel *result) {
                                          if ([result.code integerValue] == 200) {
                                              [SVProgressHUD dismiss];
                                              self.SiteWorkContent = result.details.Task_SiteWorkContent;
                                              int isDayuDate = [GlobalUtil compareDate:result.details.Task_UpDateTime withDate:self.sendTimeStr];
                                              if (isDayuDate != 1) {
                                                  [self loadCreateViewController:YES];
                                              }else{
                                              
                                                  [self loadCreateViewController:NO];
                                              }
                                              [self loadCreatePicInfoList];
                                              
                                          }
                                      }
                                      failure:^(NSError *err) {
                                          [SVProgressHUD showErrorWithStatus:@"对不起,网络错误!"];
                                          [self loadCreateViewController:NO];
                                      }];

    }else if(self.pushType == QY_JUMP_QUERYRESULT){
    
        [self loadCreateViewController:YES];
    }

}

/**获取图文详情*/
-(void)loadCreatePicInfoList{

    [NetworkAPI getJobPunishListWithTaskId:self.taskId
                                      type:@"4"
                                   success:^(HXJobPunishDetailsModel *result) {
                                       if ([result.code integerValue] == 200) {
                                           
                                           [self.collectionViewDataArray removeAllObjects];
                                           [self.collectionViewDataArray addObjectsFromArray:result.resultlist];
                                           //逆向遍历
                                           NSEnumerator *enumerator = [self.collectionViewDataArray reverseObjectEnumerator];
                                           self.collectionViewDataArray = (NSMutableArray*)[enumerator allObjects];
                                            self.qyCollectionView.dataArray = self.collectionViewDataArray;
                                           
                                           if (self.collectionViewDataArray.count > 0) {
                                               
                                               [self loadCreateShowSendPicInfo:self.collectionViewDataArray[0]];
                                           }
                                       }
                                   }
                                   failure:^(NSError *err) {
                                       
                                   }];
}

/**报告取证*/
-(void)baoGaoQuZhengBtnAct{
    HXReportEvidenceViewController * vc = [[HXReportEvidenceViewController alloc] initWithAddress:self.companyName withCon_Title:self.addressString withCon_TaskID:self.taskId];
    vc.type = CompanyReportType;
    [self.navigationController pushViewController:vc animated:YES];
}

-(void)viewDidAppear:(BOOL)animated{

    [super viewDidAppear:animated];
    self.navigationController.navigationBar.translucent = NO;

}
-(void)viewWillAppear:(BOOL)animated{

    [super viewWillAppear:animated];
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
